﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.ZWHY;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 中文会议操作对象
    /// </summary>
    private ZWHY_DAO zwhyDAO = new ZWHY_DAO();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        String currentSYBM = (String)Request["sybm"];
        if (null == currentSYBM || "".Equals(currentSYBM))
        {
            String message = "错误：没有找到当前索引编码对应的中文会议索引";
            Response.Redirect(GlobalResource.ERROR_PAGE+"?message="+message);
            return;
        }

        //添加返回按钮
        this.backHyperLink.NavigateUrl = GlobalZWHY.LISTSYML_PAGE + "?catalog=" + currentSYBM.Split('-')[0];

        //获取中文会议索引目录
        ZWHY_SYML zwhySYML = this.zwhyDAO.getZwhySYMLBySybm(currentSYBM);

        if (null == zwhySYML)
        {
            String message = "错误：没有找到当前索引编码对应的中文会议索引";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }


      
        
        //中文名称
        this.zwmcTextBox.Text = zwhySYML.zwmc;
        //外文名称
        this.wwmcTextBox.Text = zwhySYML.wwmc;

        //ZWQK_PM zwqkPM = this.zwqkDAO.getMaxZwqkPM(currentSYBM, "2000", "01");
        //索引编码
        this.sybmTextBox.Text = zwhySYML.sybm;

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;


        //设置文件名和篇号
        this.InitPH();
        this.SetWJM();
        //中文篇名
        this.zwpmTextBox.Text = "";
        //外文篇名
        this.wwpmTextBox.Text = "";
        //页数
        this.ysTextBox.Text = "";
        //作者
        this.zzTextBox.Text = "";
        //作者单位
        this.zzdwTextBox.Text = "";
        //中文文摘
        this.zwwzTextBox.Text = "";
        //中文主题词
        this.zwztcTextBox.Text = "";
        //外文文摘
        this.wwwzTextBox.Text = "";
        //外文主题词
        this.wwztcTextBox.Text = "";

        //国图分类
        this.gtflTextBox.Text = "";
        //馆藏号
        this.gchTextBox.Text = "";
    }

    /// <summary>
    /// 从页面中读取片名的信息
    /// </summary>
    /// <returns>返回片名对象</returns>
    private ZWHY_PM GetZWHY_PM()
    {
        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return null;
        }

        ZWHY_PM zwhyPM = new ZWHY_PM();

        //登录人
        zwhyPM.dlr = user.name;
        //索引编码
        zwhyPM.sybm = this.sybmTextBox.Text.Trim();
        //页数
        try
        {
            zwhyPM.ys = Int32.Parse(this.ysTextBox.Text.Trim());
        }
        catch (Exception)
        {
        }

        //文件名
        zwhyPM.wjm = this.wjmTextBox.Text.Trim();
        //原文件名
        zwhyPM.ywjm = this.ywjmHiddenField.Value.Trim();

        //中文篇名
        zwhyPM.zwpm = this.zwpmTextBox.Text.Trim();
        //外文篇名
        zwhyPM.wwpm = this.wwpmTextBox.Text.Trim();
        //作者
        zwhyPM.zz = this.zzTextBox.Text.Trim();
        //作者单位
        zwhyPM.zzdw = this.zzdwTextBox.Text.Trim();
        //中文文摘
        zwhyPM.zwwz = this.zwwzTextBox.Text.Trim();
        //外文文摘
        zwhyPM.wwwz = this.wwwzTextBox.Text.Trim();
        //中文主题词
        zwhyPM.zwztc = this.zwztcTextBox.Text.Trim();
        //外文主题词
        zwhyPM.wwztc = this.wwztcTextBox.Text.Trim();

        //国图分类
        zwhyPM.gtfl = this.gtflTextBox.Text.Trim();
        //馆藏号
        zwhyPM.gch = this.gchTextBox.Text.Trim();
        //更新日期
        zwhyPM.gxrq = DateTime.Today;

        return zwhyPM;
    }
    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证中文篇名
        if (!this.ValidateZWPM())
        {
            return;
        }

        //验证文件名
        if (!this.ValidateWJM())
        {
            return;
        }
        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        //判断要上传的文件是否已经上传过
        if (IsDuplicate(this.ywjmFileUpload.FileName))
        {
            return;
        }
        //获取中文会议篇名信息
        ZWHY_PM zwhyPM = this.GetZWHY_PM();

        //上传文件
        if (OperationFile.Upload(this.ywjmFileUpload, zwhyPM.wjm))
        {
            //存储中文会议篇名信息
            this.zwhyDAO.insertZwhyPM(zwhyPM);

            Response.Write("<Script>alert('添加中文会议篇名信息成功')</Script>");
            //设置下一篇名
            this.BindData();
        }
        else
        {
            String message = "错误：添加中文会议篇名信息失败";
            Response.Redirect(GlobalResource.ERROR_PAGE+"?message="+message);
            return;
        }
        
    }
    /// <summary>
    /// 验证中文篇名
    /// </summary>
    /// <returns>验证是否通过</returns>
    private Boolean ValidateZWPM()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.zwpmTextBox.Text || "".Equals(this.zwpmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：中文篇名不能为空";
            flag = false;
        }
        else
        {
            if (!this.zwhyDAO.ValidateZWHY_PM(this.wjmTextBox.Text,this.zwpmTextBox.Text.Trim()))
            {
                this.errorLabel.Text = "错误：该中文篇名已存在";
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证文件名
    /// </summary>
    /// <returns>验证是否通过</returns>
    private Boolean ValidateWJM()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.wjmTextBox.Text || "".Equals(this.wjmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：文件名不正确";
            flag = false;
        }
        else
        {
            ZWHY_PM zwhyPM = this.zwhyDAO.getZwhyPMByWjm(this.wjmTextBox.Text.Trim());
            if (null != zwhyPM)
            {
                this.errorLabel.Text = "错误：文件名已存在";
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            this.errorLabel.Text = "错误：请选择上传的文件";
            flag = false;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                    this.ywjmHiddenField.Value = this.ywjmFileUpload.FileName;
                }
               
                pdf.Close();
            }
        }
        return flag;
    }

    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }


    /// <summary>
    /// 初始化篇号列表
    /// </summary>
    private void InitPH()
    {
        //清空phDropDownList的选择项
        this.phDropDownList.Items.Clear();
        //目录文件名
        String catalogWjm = this.sybmTextBox.Text +  "-0000.PDF";
        //获取流水号为0000的篇名
        ZWHY_PM zwhyPM = this.zwhyDAO.getZwhyPMByWjm(catalogWjm);
        if (null == zwhyPM)
        {
            this.phDropDownList.Items.Add("0000");
            //this.phDropDownList.Items[0].Selected = true;
        }

        //获取中文期最大文件名得篇名
        zwhyPM = this.zwhyDAO.getMaxZwhyPM(this.sybmTextBox.Text);
        //没有找到则设为第一个篇名
        if (null == zwhyPM)
        {
            this.phDropDownList.Items.Add("0001");
        }
        //找到了则为最大篇号+1
        else
        {

            int endIndex = zwhyPM.wjm.LastIndexOf(".");

            String phString = zwhyPM.wjm.Substring(endIndex - 4, 4);

            int ph = 0;

            try
            {
                ph = Int32.Parse(phString);
            }
            catch (Exception)
            {
                return;
            }

            //当前篇号+1
            ph += 1;

            phString = ph.ToString();
            //长度为1
            if (phString.Length == 1)
            {
                phString = "000" + phString;
            }
            else if (phString.Length == 2)
            {
                phString = "00" + phString;
            }
            else if (phString.Length == 3)
            {
                phString = "0" + phString;
            }
            else if (phString.Length > 4)
            {
                String message = "错误：篇名数量已经超过了10000篇";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }
            this.phDropDownList.Items.Add(phString);
            //this.phDropDownList.Items[this.phDropDownList.Items.Count-1].Selected = true;
        }
        //如果只有一个选项则，选择该选项
        this.phDropDownList.Items[0].Selected = true;

    }

    /// <summary>
    /// 设置文件名
    /// </summary>
    private void SetWJM()
    {
        this.wjmTextBox.Text = this.sybmTextBox.Text + "-" + this.phDropDownList.SelectedItem.Value + ".PDF";
    }

    /// <summary>
    /// 作者内容发生变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void zzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzTextBox.Text = GlobalMethod.Semicolon(this.zzTextBox.Text);
    }
    protected void zzdwTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzdwTextBox.Text = GlobalMethod.Semicolon(this.zzdwTextBox.Text);
    }
    protected void zwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zwztcTextBox.Text = GlobalMethod.Semicolon(this.zwztcTextBox.Text);
    }
    protected void wwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.wwztcTextBox.Text = GlobalMethod.Semicolon(this.wwztcTextBox.Text);
    }
    protected void phDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.SetWJM();
    }

    /// <summary>
    /// 判断输入文件是否已经上传过，判重标准：原文件名、文件大小、页数都相同
    /// </summary>
    /// <param name="ywjm"></param>
    /// <returns>true表示有重复；false是无重复</returns>
    private Boolean IsDuplicate(String ywjm)
    {
        this.errorLabel.Text = "";
        Boolean flag = false;
        IList<ZWHY_PM> list = this.zwhyDAO.getZwhyPMByYwjm(ywjm);
        //读取上传文件的信息：文件大小及页数
        PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
        int size = pdf.FileLength;
        int pageCount = pdf.NumberOfPages;
        pdf.Close();

        //判重，判重准则：相同原文件名的PDF文件文件大小和页数都相同则为重复文件
        String filePath = null;
        foreach (ZWHY_PM zwhyPM in list)
        {
            filePath = OperationFile.FormatPath(zwhyPM.wjm)+zwhyPM.wjm;
            try
            {
                pdf = new PdfReader(filePath);
                if (null != pdf)
                {
                    if (size == pdf.FileLength && pageCount == pdf.NumberOfPages)
                    {
                        flag = true;
                    }
                }
                pdf.Close();
            }
            catch (Exception)
            {
            }
            //flag为true，则说明已经找到重复
            if (flag)
            {
                this.errorLabel.Text = "错误：你选择上传的文件已经上传过了";
                break;
            }
        }

        return flag;
    }
  
}